package com.shopx.auth.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.shopx.auth.DTO.LoginMngDTO;
import com.shopx.auth.DTO.RegDTO;
import com.shopx.auth.bean.*;
import com.shopx.auth.dao.db1.*;
import com.shopx.auth.model.*;
import com.shopx.auth.service.*;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.OriginException;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.service.ISysSeqService;
import com.shopx.cmm.DTO.PageDTO;
import com.shopx.core.common.CommonConstant;
import com.shopx.core.utils.DateTimeUtil;
import com.shopx.core.utils.ExcelUtil;
import com.shopx.core.utils.StringUtil;
import com.shopx.dal.redis.CacheServiceFactory;
import com.shopx.dal.redis.RedisCacheService;
import com.shopx.sys.bean.SysCompany;
import com.shopx.sys.model.SysCompanyModel;
import com.shopx.sys.service.ISysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author lituo
 * @className: SysConfigServiceImpl
 * @description: 用户服务
 * @date 2021/12/5 11:24 AM
 */
@Service
@Slf4j
public class SysUserServiceImpl extends BaseAuthService implements ISysUserService {

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysUserOrgDao sysUserOrgDao;

    @Resource
    private SysUserCpDao sysUserCpDao;

    @Resource
    private SysUserAddDao sysUserAddDao;

    @Resource
    private ISysCompanyService sysCompanyService;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private SysOrgDao sysOrgDao;

    @Resource
    private ISysSeqService sysSeqService;

    @Resource
    private ISysUrlService sysUrlService;

    @Resource
    private SysRoleDao sysRoleDao;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysUserCpService sysUserCpService;

    @Resource
    private ISysLoginTokenService sysLoginTokenService;

    @Resource
    private ISysUserAddService sysUserAddService;

    @Resource
    private RedisCacheService redisCacheService;

    @Value("${spring.profiles.active:prod}")
    private String environment;


    @Override
//  @Cacheable(value = CommonConstant.CacheKey.CMM, key = "'USER_USERID'+#sysUser.userId")
    public SysUserModel selectByPrimaryKey(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        sysUser.setCpId(super.getUserCpId());
        SysUserModel sum = sysUserDao.selectByPrimaryKey(sysUser);
        SysUserRoleModel sysUserRoleParm = new SysUserRoleModel();
        sysUserRoleParm.setUserId(sysUser.getUserId());
        List<SysUserRoleModel> list = sysUserRoleDao.selectList(sysUserRoleParm);
        String roleCodes = "";
        for (SysUserRoleModel model : list) {
            roleCodes += model.getRoleCode() + ",";
        }
        if (!StringUtil.isEmpty(roleCodes)) {
            sum.setRoleCodes(roleCodes.substring(0, roleCodes.length() - 1));
        } else {
            sum.setRoleCodes(roleCodes);
        }
        //查询用户附加信息
        SysUserAdd sysUserAdd = new SysUserAdd();
        sysUserAdd.setUserId(sum.getUserId());
        SysUserAdd sua = sysUserAddService.selectByPrimaryKey(sysUserAdd);
        sum.setUserAdd(sua);
        //查询用户组织机构
        //查询公司部门信息
        SysUserOrgModel sysUserOrg = new SysUserOrgModel();
        sysUserOrg.setUserId(sum.getUserId());
        sysUserOrg.setCpId(super.getUserCpId());
        List<SysUserOrgModel> suomList = sysUserOrgDao.selectList(sysUserOrg);
        List suomSortList = this.sortOrgTree(suomList);
        sum.setOrgList(suomSortList);
        String orgIds = "";
        for (SysUserOrgModel model : suomList) {
            orgIds += model.getOrgId() + ",";
        }
        sum.setOrgIds(orgIds.substring(0, orgIds.length() - 1));
        return sum;
    }


    private List<SysUserOrgModel> sortOrgTree(List<SysUserOrgModel> suomList) {
        // 1. 构建父部门ID到子部门列表的映射
        Map<String, List<SysUserOrgModel>> parentMap = new HashMap<>();
        suomList.forEach(org ->
                parentMap.computeIfAbsent(org.getParOrgId(), k -> new ArrayList<>())
                        .add(org));

        // 2. 对每个父部门的子部门列表排序
        parentMap.values().forEach(children ->
                children.sort(Comparator.comparingInt(SysUserOrgModel::getOrgSort)));

        // 3. 获取根部门（假设根部门parOrgId为null或"0"）
        List<SysUserOrgModel> rootOrgs = parentMap.getOrDefault(null,
                parentMap.getOrDefault("0", new ArrayList<>()));

        // 4. 递归构建有序列表
        List<SysUserOrgModel> result = new ArrayList<>();
        if (rootOrgs != null) {
            rootOrgs.forEach(root -> addChildrenToList(result, root, parentMap));
        }
        return result;
    }

    private void addChildrenToList(List<SysUserOrgModel> result,
                                   SysUserOrgModel parent,
                                   Map<String, List<SysUserOrgModel>> parentMap) {
        result.add(parent);
        List<SysUserOrgModel> children = parentMap.get(parent.getOrgId());
        if (children != null) {
            children.forEach(child -> addChildrenToList(result, child, parentMap));
        }
    }

    @Override
    public SysUserModel selectOne(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        sysUser.setCpId(super.getUserCpId());
        SysUserModel sum = sysUserDao.selectByPrimaryKey(sysUser);
        return sum;
    }

    @Override
    public SysUserModel selectSimpleInfo(SysUser sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        SysUserModel sum = sysUserDao.selectSimpleInfo(sysUser);
        return sum;
    }


    @Override
    public SysUserModel selectUser(SysUserModel sysUserModel) throws ShopxException {
        SysUserModel su = new SysUserModel();
        su.setUserId(sysUserModel.getUserId());
        su.setCpId(super.getUserCpId());
        SysUser record = sysUserDao.selectByPrimaryKey(su);
        if (record == null) {
            throw new OriginException("99999", "用户不存在");
        }
        su.setLoginName(record.getLoginName());
//    su.setPassword(Md5Encrypt.md5(sysUserModel.getPassword()));
        su.setPassword(sysUserModel.getPassword());
        SysUserModel record2 = sysUserDao.officeLogin(su);
        if (record2 == null) {
            throw new OriginException("99999", "用户不存在或密码错误");
        }
        return record2;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int addByMng(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        int result = 0;
        String cpId = super.getUserCpId();
        String orgId = super.getUserOrgId();
        SysUserModel sysUserModel = sysUserDao.selectSimpleInfoByLoginName(sysUser);
        if (sysUserModel != null) {
            SysUserCpModel sysUserCpModel = new SysUserCpModel();
            sysUserCpModel.setUserId(sysUserModel.getUserId());
            sysUserCpModel.setCpId(super.getUserCpId());
            int cnt = sysUserCpService.selectCount(sysUserCpModel);
            if (cnt > 0) {
                //用户已经存在，增加角色
                this.insertUserRole(sysUserModel.getUserId(), sysUser.getRoleCodes());
                return 1;
            } else {
                sysUserCpModel.setOrgId(sysUser.getOrgId());
                sysUserCpService.insertSelective(sysUserCpModel);
                //插入角色信息
                this.insertUserRole(sysUserModel.getUserId(), sysUser.getRoleCodes());
                return 1;
            }
        }
        String id = sysSeqService.getTabSeq("SysUser", 4, null);
        log.info("user.insertSelective.id:{}", id);
        sysUser.setUserId(id);
        sysUser.setCreateUserId(super.getLoginUserId());
        if (StringUtil.isEmpty(sysUser.getPassword())) {
            //同账户名
            sysUser.setPassword(sysUser.getLoginName());
        }
//    if (StringUtil.isEmpty(sysUser.getCpAdminFlag())) {
//      sysUser.setCpAdminFlag(CommonConstant.CpAdminFlag.NO);
//    }
        sysUser.setState(CommonConstant.State.EFFECTIVE);
        sysUser.setInitPswdFlag(CommonConstant.InitPswdFlag.Y);
        result = sysUserDao.insertSelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //插入角色信息
        this.insertUserRole(id, sysUser.getRoleCodes());
        //插入附加信息
        SysUserAdd sua = new SysUserAdd();
        sua.setUserId(id);
        sua.setCreateUserId(super.getLoginUserId());
        sysUserAddService.insertSelective(sua);
        //插入t_sys_user_cp表
        SysUserCp sysUserCp = new SysUserCp();
        sysUserCp.setUserId(id);
        sysUserCp.setCpId(cpId);
//        sysUserCp.setOrgId(orgId);
        sysUserCpService.insertSelective(sysUserCp);

        return result;
    }


    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int insertSelective(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        String orgIds = sysUser.getOrgIds();
        //查询loginName是否存在，存在则判断t_sys_user_cp信息是否存在。
        //可能是一个公司已经新增了用户，但这个用户去别的公司也任职了。如供应商、如子公司等等
        SysUserModel sysUserModel = sysUserDao.selectSimpleInfoByLoginName(sysUser);
        if (sysUserModel != null) {
            //已经存在，验证是否t_sys_user_cp表存在数据，且cp一样
            SysUserCpModel sysUserCpModel = new SysUserCpModel();
            sysUserCpModel.setUserId(sysUserModel.getUserId());
            sysUserCpModel.setCpId(super.getUserCpId());
            int cnt = sysUserCpService.selectCount(sysUserCpModel);
            if (cnt > 0) {
                throw new OriginException("用户已经存在，新增失败");
            } else {
                sysUserCpModel.setOrgId(sysUser.getOrgId());
                sysUserCpService.insertSelective(sysUserCpModel);

                //插入角色信息
                this.insertUserRole(sysUserModel.getUserId(), sysUser.getRoleCodes());
                //插入用户部门信息
                List<SysUserOrg> suoList = new ArrayList<>();
                for (String orgId : orgIds.split(",")) {
                    SysUserOrg suo = new SysUserOrg();
                    suo.setUserId(sysUserModel.getUserId());
                    suo.setCpId(super.getUserCpId());
                    suo.setOrgId(orgId);
                    suoList.add(suo);
                }
                sysUserOrgDao.insertBatch(suoList);
                return 1;
            }
        }

        //不存在，新增
        String id = sysSeqService.getTabSeq("SysUser", 4, null);
        log.info("user.insertSelective.id:{}", id);
        sysUser.setUserId(id);
        sysUser.setCreateUserId(super.getLoginUserId());
        if (StringUtil.isEmpty(sysUser.getPassword())) {
            //同账户名
//      sysUser.setPassword(Md5Encrypt.md5(sysUser.getLoginName()));
            sysUser.setPassword(sysUser.getLoginName());
        }
//    if (StringUtil.isEmpty(sysUser.getCpAdminFlag())) {
//      sysUser.setCpAdminFlag(CommonConstant.CpAdminFlag.NO);
//    }
        sysUser.setState(CommonConstant.State.EFFECTIVE);
        sysUser.setInitPswdFlag(CommonConstant.InitPswdFlag.Y);
        int result = sysUserDao.insertSelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //插入角色信息
        this.insertUserRole(id, sysUser.getRoleCodes());
        //插入附加信息
//    sysUser.getUserAdd().setUserId(id);
//    sysUser.getUserAdd().setCreateUserId(super.getLoginUserId());
//    sysUserAddService.insertSelective(sysUser.getUserAdd());
        //插入t_sys_user_cp表
        SysUserCp sysUserCp = new SysUserCp();
        sysUserCp.setUserId(id);
        sysUserCp.setCpId(super.getUserCpId());
//        sysUserCp.setOrgId(sysUser.getOrgId());
        sysUserCpService.insertSelective(sysUserCp);

        //插入用户部门信息
        List<SysUserOrg> suoList = new ArrayList<>();
        for (String orgId : orgIds.split(",")) {
            SysUserOrg suo = new SysUserOrg();
            suo.setUserId(id);
            suo.setCpId(super.getUserCpId());
            suo.setOrgId(orgId);
            suoList.add(suo);
        }
        sysUserOrgDao.insertBatch(suoList);
        return result;
    }


    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public String regUser(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        String id = sysSeqService.getTabSeq("SysUser", 4, null);
        log.info("user.insertSelective.id:{}", id);
        sysUser.setUserId(id);
//    sysUser.setCpId(super.getUserInfo().getCpId());
        sysUser.setCreateUserId(super.getLoginUserId());
        if (StringUtil.isEmpty(sysUser.getPassword())) {
            //同账户名
//      sysUser.setPassword(Md5Encrypt.md5(sysUser.getLoginName()));
            sysUser.setPassword(sysUser.getLoginName());
        }
        sysUser.setInitPswdFlag(CommonConstant.InitPswdFlag.N);
        sysUser.setState(CommonConstant.State.EFFECTIVE);
        int result = sysUserDao.insertSelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        return id;
    }

    @Override
//  @CacheEvict(value = CommonConstant.CacheKey.CMM, key = "'USER_USERID'+#sysUser.userId")
    public void quit(SysUserModel sysUser) throws ShopxException {
        log.info("user.quit.id:{}", sysUser.getUserId());
        sysUser.setState(CommonConstant.UserState.QUIT);
        int result = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
    }


    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
//  @CacheEvict(value = CommonConstant.CacheKey.CMM, key = "'USER_USERID'+#sysUser.userId")
    public int updateByPrimaryKeySelective(SysUserModel sysUser) throws ShopxException {
        log.info("user.updateByPrimaryKeySelective.id:{}", sysUser.getUserId());
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        SysUserModel su = new SysUserModel();
        su.setUserId(sysUser.getUserId());
        SysUserModel sum = this.selectByPrimaryKey(su);
        if (sum == null) {
            throw new ShopxException(ResultCodeEnum.BUSI_NOT_EXISTS_RECORD);
        }
        sysUser.setUpdateUserId(super.getLoginUserId());
        int result = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //删除用户角色关系
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setCpId(super.getUserCpId());
        sysUserRoleDao.deleteByUserId(sysUserRole);
        //新增用户角色关系
        this.insertUserRole(sysUser.getUserId(), sysUser.getRoleCodes());
        //修改t_sys_user_cp表记录
        SysUserCp sysUserCp = new SysUserCp();
        sysUserCp.setUserId(sysUser.getUserId());
        sysUserCp.setCpId(super.getUserCpId());
        sysUserCpService.updateByPrimaryKeySelective(sysUserCp);
        //获取当前设置的用户组织机构编号A
        //获取修改的组织机构B
        //删除用户组织机构A，新增修改后的组织
        String userOrgIds = super.getUserOrgId();
        List<SysUserOrg> list = new ArrayList<>();
        for (String orgId : userOrgIds.split(",")) {
            SysUserOrg suo = new SysUserOrg();
            suo.setUserId(sysUser.getUserId());
            suo.setCpId(super.getUserCpId());
            suo.setOrgId(orgId);
            list.add(suo);
        }
        sysUserOrgDao.deleteBatch(list);
        List<SysUserOrg> list2 = new ArrayList<>();
        String changeOrgIds = sysUser.getOrgIds();
        for (String orgId : changeOrgIds.split(",")) {
            SysUserOrg suo = new SysUserOrg();
            suo.setUserId(sysUser.getUserId());
            suo.setCpId(super.getUserCpId());
            suo.setOrgId(orgId);
            list2.add(suo);
        }
        sysUserOrgDao.insertBatch(list2);
        //删除缓存
        redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + sysUser.getUserId());
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public int updateUserInfo(SysUser sysUser) throws ShopxException {
        log.info("user.updateUserInfo.id:{}", sysUser.getUserId());
        //查询是否存在相同的号码
        SysUserModel sum = new SysUserModel();
        sum.setUserId(sysUser.getUserId());
//    sum.setLoginName(sysUser.getLoginName());
        SysUserModel user = this.selectByPrimaryKey(sum);
        if (!user.getLoginName().equals(sysUser.getLoginName())) {
            //修改了电话号码，查询电话号码是否已经占用
            SysUserModel sum2 = new SysUserModel();
            sum2.setLoginName(sysUser.getLoginName());
            int cnt = this.selectCount(sum2);
            if (cnt > 0) {
                throw new OriginException("电话号码已经被人使用，请换一个号码");
            }
        }
        SysUserModel su = new SysUserModel();
        su.setUserId(sysUser.getUserId());
        su.setLoginName(sysUser.getLoginName());
        su.setPassword(sysUser.getPassword());
        int result = sysUserDao.updateByPrimaryKeySelective(su);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //删除缓存
        redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + sysUser.getUserId());
        return result;
    }

    @Override
    public int updateIdCard(SysUser sysUser) throws ShopxException {
        log.info("user.updateIdCard.id:{}", sysUser.getUserId());
        SysUser sysUserParam = new SysUser();
        sysUserParam.setUserId(sysUser.getUserId());
        sysUserParam.setIdcard(sysUser.getIdcard());
        sysUserParam.setIdcardFront(sysUser.getIdcardFront());
        sysUserParam.setIdcardBack(sysUser.getIdcardBack());
        int result = sysUserDao.updateByPrimaryKeySelective(sysUserParam);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //删除缓存
        redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + sysUser.getUserId());
        return result;
    }

    @Override
    public int updateState(SysUserModel sysUser) throws ShopxException {
        log.info("user.updateState.id:{}", sysUser.getUserId());
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        //查询用户基本信息
        SysUserModel su = new SysUserModel();
        su.setUserId(sysUser.getUserId());
        SysUserModel sum = this.selectByPrimaryKey(su);
        if (sum == null) {
            throw new ShopxException(ResultCodeEnum.BUSI_NOT_EXISTS_RECORD);
        }
        //验证是否为管理员
        //如果是管理员，只有管理员自己能操作
//    if (CommonConstant.CpAdminFlag.YES.equals(sum.getCpAdminFlag())) {
//      throw new OriginException("对不起，您没权限修改管理员信息");
//    }

        sysUser.setUpdateUserId(super.getLoginUserId());
        if (CommonConstant.State.EFFECTIVE.equals(sysUser.getState())) {
            if (CommonConstant.State.EFFECTIVE.equals(sum.getState())) {
                throw new OriginException("员工已经是在职状态");
            }
            sysUser.setQuitTm(" ");
        } else if (CommonConstant.State.INVALID.equals(sysUser.getState())) {
            if (CommonConstant.State.INVALID.equals(sum.getState())) {
                throw new OriginException("员工已经是离职状态");
            }
            sysUser.setQuitTm(DateTimeUtil.getDate8());
        }
        int result = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
        //删除缓存
        redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + sysUser.getUserId());
        return result;
    }

    /***
     * @description:新增用户角色信息
     *
     * @param userId
     * @param roleCodes
     * @author:lituo
     * @date:2021-01-08 4:57 PM
     * @return:void
     */
    private void insertUserRole(String userId, String roleCodes) {
        log.info("user.add.role");
        if (StringUtil.isEmpty(roleCodes)) {
            throw new OriginException("99999", "请至少选择一个角色");
        }
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (String roleCode : roleCodes.split(",")) {
            if (StringUtil.isEmpty(roleCode)) {
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleCode(roleCode);
            sysUserRole.setCpId(super.getUserCpId());
            list.add(sysUserRole);
        }
        int result = sysUserRoleDao.insertBatch(list);
        if (result <= 0) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
//  @CacheEvict(value = CommonConstant.CacheKey.CMM, key = "'USER_USERID'+#sysUser.userId")
    public int deleteByPrimaryKey(SysUser sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        SysUserModel su = new SysUserModel();
        su.setUserId(sysUser.getUserId());
        SysUserModel sum = this.selectByPrimaryKey(su);
        if (sum == null) {
            throw new ShopxException(ResultCodeEnum.BUSI_NOT_EXISTS_RECORD);
        }
        //如果是管理员，只有管理员自己能操作
//    if (CommonConstant.CpAdminFlag.YES.equals(sum.getCpAdminFlag())) {
//      if (!super.getLoginUserId().equals(sum.getUserId())) {
//        throw new OriginException("对不起，您没权限修改管理员信息");
//      }
//    }
        int result = sysUserDao.deleteByPrimaryKey(sysUser);
        if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }

        //删除用户角色关系
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setCpId(super.getUserCpId());
        sysUserRoleDao.deleteByUserId(sysUserRole);

        //删除缓存
        redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + sysUser.getUserId());
        return result;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public void deleteBatch(List<SysUser> list) {
        if (list == null || list.size() == 0) {
            throw new OriginException("至少删除一条记录");
        }
        //自己不能删除自己的账号
        for (SysUser su : list) {
            if (super.getLoginUserId().equals(su.getUserId())) {
                throw new OriginException("不能删除自己的账号");
            }
            //删除缓存
            redisCacheService.del(CommonConstant.CacheKey.USER_CACHE + su.getUserId());
        }
        sysUserDao.deleteBatch(list);
    }

    @Override
    public List<SysUserModel> queryList(SysUserModel sysUser) throws ShopxException {
//    sysUser.setCpId(super.getUserCpId());
        sysUser.setState(CommonConstant.UserState.EFFECTIVE);
        if (!StringUtil.isEmpty(sysUser.getRoleCodes())) {
            String roleCodes = sysUser.getRoleCodes();
            int length = roleCodes.split(",").length;
            String[] roleCodesChk = new String[length];
            for (int i = 0; i < length; i++) {
                roleCodesChk[i] = roleCodes.split(",")[i];
            }
            sysUser.setRoleCodesChk(roleCodesChk);
        }
        List<SysUserModel> list = this.selectList(sysUser);
        return list;
    }

    @Override
    public List<SysUserModel> queryOrgUserList(SysUserModel sysUser) throws ShopxException {
//    sysUser.setCpId(super.getUserCpId());
        String orgId = super.getUserOrgId();
        //查询下级部门
        SysOrgModel sysOrgModel = new SysOrgModel();
        sysOrgModel.setRootId(orgId);
        List<SysOrgModel> list = sysOrgDao.selectOrgTreeList(sysOrgModel);
        if (list != null && list.size() > 0) {
            String[] orgIdChk = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                orgIdChk[i] = list.get(i).getOrgId();
            }
            sysUser.setOrgIdChk(orgIdChk);
        }
        if (!StringUtil.isEmpty(sysUser.getRoleCodes())) {
            String roleCodes = sysUser.getRoleCodes();
            int length = roleCodes.split(",").length;
            String[] roleCodesChk = new String[length];
            for (int i = 0; i < length; i++) {
                roleCodesChk[i] = roleCodes.split(",")[i];
            }
            sysUser.setRoleCodesChk(roleCodesChk);
        }
        List<SysUserModel> userList = this.selectList(sysUser);
        return userList;
    }

    private int selectCount(SysUserModel sysUser) throws ShopxException {
        sysUser.setCpId(super.getUserCpId());
        return sysUserDao.selectCount(sysUser);
    }

    /**
     * 分页展示用户角色
     *
     * @param sysUser
     * @return
     * @auth lituo
     * @date 2022/8/12
     **/
    private List<SysUserModel> selectListByPage(SysUserModel sysUser) throws ShopxException {
        sysUser.setCpId(super.getUserCpId());
        List<SysUserModel> list = sysUserDao.selectList(sysUser);
        for (SysUserModel model : list) {
            SysUserRoleModel sysUserRole = new SysUserRoleModel();
            sysUserRole.setUserId(model.getUserId());
            sysUserRole.setCpId(super.getUserCpId());
            String roleNames = sysUserRoleService.selectRoleByUserId(sysUserRole);
            model.setRoleNames(roleNames);
        }
        return list;
    }

    private List<SysUserModel> selectList(SysUserModel sysUser) throws ShopxException {
        sysUser.setCpId(super.getUserCpId());
        List<SysUserModel> list = sysUserDao.selectList(sysUser);
//    for (SysUserModel model : list) {
        //查询用户对应的角色(非常耗时间 暂时去掉) TODO
//      SysUserRoleModel sysUserRole = new SysUserRoleModel();
//      sysUserRole.setUserId(model.getUserId());
//      String roleNames = sysUserRoleService.selectRoleByUserId(sysUserRole);
//      model.setRoleNames(roleNames);
//    }
        return list;
    }

    @Override
    public PageDTO<SysUserModel> getListPage(SysUserModel sysUser) throws ShopxException {
        if (sysUser == null) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        if (!StringUtil.isEmpty(sysUser.getRoleCodes())) {
            String roleCodes = sysUser.getRoleCodes();
            int length = roleCodes.split(",").length;
            String[] roleCodesChk = new String[length];
            for (int i = 0; i < length; i++) {
                roleCodesChk[i] = roleCodes.split(",")[i];
            }
            sysUser.setRoleCodesChk(roleCodesChk);
        }
        sysUser.setCpId(super.getUserCpId());
        PageDTO<SysUserModel> pageDTO = new PageDTO<SysUserModel>();

        //获取组织机构
        String orgIds[] = super.queryCondOrgIds(sysUser.getOrgId());
        sysUser.setOrgIdChk(orgIds);

        //角色数据范围可见调整
        //超级管理员，可以看到所有数据
        //管理员，可以看到除超级管理员之外所有的数据
        //其余角色，看不到超级管理员和管理员数据
        boolean superadminFlag = super.hasRole(CommonConstant.RoleCode.SUPER_ADMIN);
        boolean adminFlag = super.hasRole(CommonConstant.RoleCode.ENT_ADMIN);
        if (superadminFlag) {
            //全部权限
        } else if (adminFlag) {
            String roleCode[] = new String[]{CommonConstant.RoleCode.SUPER_ADMIN};
            sysUser.setExcloudRoleCode(roleCode);
        } else {
            String roleCode[] = new String[]{CommonConstant.RoleCode.SUPER_ADMIN, CommonConstant.RoleCode.ENT_ADMIN};
            sysUser.setExcloudRoleCode(roleCode);
        }
        pageDTO.setiTotalDisplayRecords(selectCount(sysUser));
        pageDTO.setData(selectListByPage(sysUser));
        return pageDTO;
    }

    /**
     * @return void
     * @desc 验证用户登录
     * @author lituo
     * @date 2023/5/23 10:35 下午 @param dto
     */
    private SysUserModel checkUserLogin(LoginMngDTO dto) {
        if (!"dev".equals(environment)) {
            //测试环境不需要填写验证码
            //验证随机验证码是否有效
            String codeKey = dto.getCodeKey();
            String randomCode = dto.getRandomCode();
            if (CacheServiceFactory.getCacheService().get(codeKey) == null) {
                throw new OriginException("90000", "验证码已经失效，请您刷新页面后重试");
            }
            String code = (String) CacheServiceFactory.getCacheService().get(codeKey);
            if (!code.equals(randomCode)) {
                log.error("验证码不正确.code:{},randomCode:{}", code, randomCode);
                CacheServiceFactory.getCacheService().del(codeKey);
                throw new OriginException("90000", "验证码不正确，请您刷新页面后重试");
            }
            //验证成功，删除验证码
            CacheServiceFactory.getCacheService().del(codeKey);
        }
        SysUserModel sum = new SysUserModel();
        sum.setLoginName(dto.getLoginName());
//    sum.setPassword(Md5Encrypt.md5(dto.getPassword()));
        sum.setPassword(dto.getPassword());
        sum.setCpId(dto.getCpId());
        SysUserModel user = sysUserDao.officeLogin(sum);
        if (user == null) {
            throw new OriginException("99999", "账户名和密码错误，登录失败");
        }
        return user;
    }

    @Override
    public List<SysUserCpModel> selectUserCpList(LoginMngDTO loginMngDTO) {
//    SysUserModel sum = this.checkUserLogin(loginMngDTO);
        SysUser su = new SysUser();
        su.setLoginName(loginMngDTO.getLoginName());
//    su.setPassword(Md5Encrypt.md5(loginMngDTO.getPassword()));
        su.setPassword(loginMngDTO.getPassword());
        SysUserModel sum = sysUserDao.selectSimpleInfoByLogin(su);
        if (sum == null) {
            throw new OriginException("账户名和密码不匹配，登录失败");
        }
        SysUserCpModel sysUserCpModel = new SysUserCpModel();
        sysUserCpModel.setUserId(sum.getUserId());
        List<SysUserCpModel> list = sysUserCpService.selectList(sysUserCpModel);
        return list;
    }

    @Override
    public SysUserModel changeCp(String cpId) throws ShopxException {
        log.info("changeCp:{},{}", super.getLoginUserId(), cpId);
        //验证是否有权限访问
        SysUserCpModel sysUserCpModel = new SysUserCpModel();
        sysUserCpModel.setUserId(super.getLoginUserId());
        List<SysUserCpModel> cpList = sysUserCpService.selectList(sysUserCpModel);
        if (cpList.size() == 0) {
            throw new OriginException("登录账户没有对应公司访问权限，登录失败");
        }
        boolean cpMatch = false;
        String cpName = "";
        for (SysUserCpModel cpModel : cpList) {
            if (cpModel.getCpId().equals(cpId)) {
                cpMatch = true;
                cpName = cpModel.getCpName();
            }
        }
        if (!cpMatch) {
            throw new OriginException("登录账户没有对应公司访问权限，切换失败");
        }
//    SysUserModel user = super.getLoginUserInfo();
//    user.setCpName(cpName);
//    //写上下文
//    ShopxContext ctx =ShopxContext.getCurrentContext();
//    ctx.setProperty(CommonConstant.CP_ID, cpId);

        SysUserModel user = getLoginUserInfo();
        //是否是平台管理员
        boolean platAdminFlag = false;
        //获取角色信息
        SysUserRoleModel sysUserRoleParm = new SysUserRoleModel();
        sysUserRoleParm.setUserId(user.getUserId());
        sysUserRoleParm.setCpId(cpId);
        List<SysUserRoleModel> list = sysUserRoleDao.selectList(sysUserRoleParm);
        String roleCodes = "";
        String roleNames = "";
        String roleTypes = "";
        String roleTypeNames = "";
        for (SysUserRoleModel model : list) {
            roleCodes += model.getRoleCode() + ",";
            roleNames += model.getRoleName() + ",";
            roleTypes += model.getRoleType() + ",";
            if (CommonConstant.RoleType.OFFICE.equals(model.getRoleType())) {
                roleTypeNames += "工程管家" + ",";
            } else {
                roleTypeNames += model.getRoleTypeName() + ",";
            }
            if (CommonConstant.RoleCode.SUPER_ADMIN.equals(model.getRoleCode())) {
                platAdminFlag = true;
            }
        }
        if (!StringUtil.isEmpty(roleCodes)) {
            user.setRoleCodes(roleCodes.substring(0, roleCodes.length() - 1));
            user.setRoleNames(roleNames.substring(0, roleNames.length() - 1));
            user.setRoleTypes(roleTypes.substring(0, roleTypes.length() - 1));
            user.setRoleTypesName(roleTypeNames.substring(0, roleTypeNames.length() - 1));
        } else {
            user.setRoleCodes(roleCodes);
            user.setRoleNames(roleNames);
            user.setRoleTypes(roleTypes);
            user.setRoleTypesName(roleTypeNames);
        }

        //验证公司是否在合同期，是否有效
        if (!platAdminFlag) {
            //不是平台管理员，验证企业有效权限
            sysCompanyService.checkCompanyState(cpId);
        }
        // 获取菜单
        JSONArray url = sysUrlService.getUrlJsonByUserId(user.getUserId(), CommonConstant.UrlType.MENU, cpId);
        user.setRoleMenu(url.toString());
        //userId为key  tokenId为value 写入缓存
        //验证是否已经存在缓存，存在则返回（这种做法，可保证一个用户在多个地方登陆）
        String key = user.getUserId() + ":" + CommonConstant.UserType.MNG;
        String tokenId = (String) CacheServiceFactory.getCacheService().get(key);
        if (tokenId == null) {
            //不存在，则更新缓存
            tokenId = StringUtil.createRandomCharData(16);
            sysLoginTokenService.setUserTokensForRedis(tokenId, CommonConstant.UserType.MNG, user.getUserId());
        }
        user.setTokenId(tokenId);
        user.setCpId(cpId);
        //查询公司名称
        SysCompany sysCompany = new SysCompany();
        sysCompany.setCpId(cpId);
        SysCompanyModel cpModel = sysCompanyService.selectByPrimaryKey(sysCompany);
        if (cpModel != null) {
            user.setCpName(cpModel.getCpName());
        }
        //查询公司列表
        user.setCpList(cpList);
        return user;
    }

    @Override
    public String changeRoleType(String roleType) throws ShopxException {
        log.info("changeRoleType:{},{}", super.getLoginUserId(), roleType);
        //查询是否有此角色
        SysUserRoleModel surm = new SysUserRoleModel();
        surm.setUserId(super.getLoginUserId());
        surm.setCpId(super.getUserCpId());
        List<SysUserRoleModel> list = sysUserRoleDao.selectList(surm);
        if (list == null || list.size() == 0) {
            throw new OriginException("登录账户没有对应公司岗位访问权限，切换失败");
        }
        //验证是否存在岗位
        boolean matchRole = false;
        for (SysUserRoleModel model : list) {
            if (model.getRoleType().equals(roleType)) {
                matchRole = true;
                break;
            }
        }
        if (!matchRole) {
            throw new OriginException("登录账户没有对应公司岗位访问权限，切换失败");
        }
        return roleType;
    }


    @Override
    public SysUserModel officeLogin(LoginMngDTO dto) throws ShopxException {
        if (dto == null) {
            throw new OriginException("99999", "请输入用户名密码");
        }
        log.info("webLogin.begin.loginName:{}", dto.getLoginName());
        //测试环境不需要验证验证码
        SysUserModel user = this.checkUserLogin(dto);
        if (!CommonConstant.State.EFFECTIVE.equals(user.getState())) {
            throw new OriginException("99999", "账户已失效，请联系管理员");
        }
        //验证用户和公司的关系
        SysUserCpModel sysUserCpModel = new SysUserCpModel();
        sysUserCpModel.setUserId(user.getUserId());
        List<SysUserCpModel> cpList = sysUserCpService.selectList(sysUserCpModel);
        if (cpList.size() == 0) {
            throw new OriginException("登录账户没有对应公司访问权限，登录失败");
        }
        boolean cpMatch = false;
        for (SysUserCpModel cpModel : cpList) {
            if (cpModel.getCpId().equals(dto.getCpId())) {
                cpMatch = true;
                break;
            }
        }
        if (!cpMatch) {
            throw new OriginException("登录账户没有对应公司访问权限，登录失败");
        }

        //验证openId是否存在，不存在则更新
        String openId = dto.getOpenId();
        if (StringUtil.isEmpty(user.getOpenId()) && !StringUtil.isEmpty(openId)) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(user.getUserId());
            sysUser.setOpenId(openId);
            int result = sysUserDao.updateByPrimaryKeySelective(sysUser);
            if (result != 1) {
                throw new ShopxException(ResultCodeEnum.DB_ERROR);
            }
        }

        //是否是平台管理员
        boolean platAdminFlag = false;
        //获取角色信息
        SysUserRoleModel sysUserRoleParm = new SysUserRoleModel();
        sysUserRoleParm.setUserId(user.getUserId());
        sysUserRoleParm.setCpId(dto.getCpId());
        List<SysUserRoleModel> list = sysUserRoleDao.selectList(sysUserRoleParm);
        if (list.size() == 1) {
            user.setCurRoleType(list.get(0).getRoleType());
        } else {
            //如果是多个角色，但是类型一样，也需要写入
            boolean setFlag = true;
            String roleType = list.get(0).getRoleType();
            for (SysUserRoleModel surm : list) {
                if (!roleType.equals(surm.getRoleType())) {
                    setFlag = false;
                    break;
                }
            }
            if (setFlag) {
                user.setCurRoleType(list.get(0).getRoleType());
            }
        }
        String roleCodes = "";
        String roleNames = "";
        String roleTypes = "";
        String roleTypeNames = "";
        for (SysUserRoleModel model : list) {
            roleCodes += model.getRoleCode() + ",";
            roleNames += model.getRoleName() + ",";
            if (roleTypes.indexOf(model.getRoleType()) == -1) {
                roleTypes += model.getRoleType() + ",";
                if (CommonConstant.RoleType.OFFICE.equals(model.getRoleType())) {
                    roleTypeNames += "工程管家" + ",";
                } else {
                    roleTypeNames += model.getRoleTypeName() + ",";
                }
            }
            if (CommonConstant.RoleCode.SUPER_ADMIN.equals(model.getRoleCode())) {
                platAdminFlag = true;
            }
        }
        if (!StringUtil.isEmpty(roleCodes)) {
            user.setRoleCodes(roleCodes.substring(0, roleCodes.length() - 1));
            user.setRoleNames(roleNames.substring(0, roleNames.length() - 1));
            user.setRoleTypes(roleTypes.substring(0, roleTypes.length() - 1));
            user.setRoleTypesName(roleTypeNames.substring(0, roleTypeNames.length() - 1));
        } else {
            user.setRoleCodes(roleCodes);
            user.setRoleNames(roleNames);
            user.setRoleTypes(roleTypes);
            user.setRoleTypesName(roleTypeNames);
        }

        //验证公司是否在合同期，是否有效
        if (!platAdminFlag) {
            //不是平台管理员，验证企业有效权限
            sysCompanyService.checkCompanyState(dto.getCpId());
        }
        // 获取菜单
        JSONArray url = sysUrlService.getUrlJsonByUserId(user.getUserId(), CommonConstant.UrlType.MENU, dto.getCpId());
        user.setRoleMenu(url.toString());
        //userId为key  tokenId为value 写入缓存
        //验证是否已经存在缓存，存在则返回（这种做法，可保证一个用户在多个地方登陆）
        String key = user.getUserId() + ":" + CommonConstant.UserType.MNG;
        String tokenId = (String) CacheServiceFactory.getCacheService().get(key);
        if (tokenId == null) {
            //不存在，则更新缓存
            tokenId = StringUtil.createRandomCharData(16);
            sysLoginTokenService.setUserTokensForRedis(tokenId, CommonConstant.UserType.MNG, user.getUserId());
        }
        user.setTokenId(tokenId);
        user.setCpId(dto.getCpId());
        //查询公司名称
        SysCompany sysCompany = new SysCompany();
        sysCompany.setCpId(dto.getCpId());
        SysCompanyModel cpModel = sysCompanyService.selectByPrimaryKey(sysCompany);
        if (cpModel != null) {
            user.setCpName(cpModel.getCpName());
        }
        //查询公司列表
        user.setCpList(cpList);
        //查询公司部门信息
        SysUserOrgModel sysUserOrg = new SysUserOrgModel();
        sysUserOrg.setUserId(user.getUserId());
        sysUserOrg.setCpId(super.getUserCpId());
        List<SysUserOrgModel> suomList = sysUserOrgDao.selectList(sysUserOrg);
        List suomSortList = this.sortOrgTree(suomList);
        user.setOrgList(suomSortList);
        String orgIds = "";
        for (SysUserOrgModel model : suomList) {
            orgIds += model.getOrgId() + ",";
        }
        user.setOrgIds(orgIds.substring(0, orgIds.length() - 1));
        return user;
    }


    @Override
    public void changePswd(SysUserModel userModel) throws ShopxException {
        log.info("user.changePswd.begin.userId:{}", super.getLoginUserId());
        if (StringUtil.isEmpty(userModel.getPassword())) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        //验证密码长度，字母+数字
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        if (!userModel.getPassword().matches(regex)) {
            throw new OriginException("密码由字母+数字组成，长度小于等于16位，大于等于6位");
        }
//    userModel.setPassword(Md5Encrypt.md5(userModel.getPassword()));
        userModel.setPassword(userModel.getPassword());
        userModel.setUserId(super.getLoginUserId());
        userModel.setInitPswdFlag(CommonConstant.InitPswdFlag.N);
        int result = sysUserDao.updateByPrimaryKeySelective(userModel);
        if (result != 1) {
            throw new OriginException("99999", "修改密码失败");
        }
        //修改令牌，重新登录
        String tokenId = StringUtil.createRandomCharData(16);
        sysLoginTokenService.setUserTokensForRedis(tokenId, CommonConstant.UserType.MNG, super.getLoginUserId());
    }

    @Override
    public void changePswdByAdmin(SysUserModel userModel) throws ShopxException {
        log.info("user.changePswd.begin.userId:{}", super.getLoginUserId());
        if (StringUtil.isEmpty(userModel.getPassword())) {
            throw new ShopxException(ResultCodeEnum.PAR_NULL);
        }
        //验证密码长度，字母+数字
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        if (!userModel.getPassword().matches(regex)) {
            throw new OriginException("密码由字母+数字组成，长度小于等于16位，大于等于6位");
        }
//    userModel.setPassword(Md5Encrypt.md5(userModel.getPassword()));
        userModel.setPassword(userModel.getPassword());
        userModel.setUserId(userModel.getUserId());
        userModel.setInitPswdFlag(CommonConstant.InitPswdFlag.N);
        int result = sysUserDao.updateByPrimaryKeySelective(userModel);
        if (result != 1) {
            throw new OriginException("99999", "修改密码失败");
        }
        String tokenId = StringUtil.createRandomCharData(16);
        sysLoginTokenService.setUserTokensForRedis(tokenId, CommonConstant.UserType.MNG, userModel.getUserId());
    }


    @Override
    public List<SysUserModel> selectListByRoleCode(SysUserModel sysUser) throws ShopxException {
        sysUser.setCpId(super.getUserCpId());
        List<SysUserModel> list = sysUserDao.selectListByRoleCode(sysUser);
        return list;
    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public void userReg(RegDTO dto) {
        log.info("userReg.begin:{}", dto.getLoginName());
        //验证参数
        if (!dto.getPassword().equals(dto.getPassword2())) {
            throw new OriginException("99999", "两次密码输入不一致");
        }
        //密码验证
        String regex2 = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        if (!dto.getPassword().matches(regex2)) {
            throw new OriginException("密码由字母+数字组成，长度小于等于16位，大于等于6位");
        }

//    String regex = "^[1](([3][0-9])|([4][5,7,9])|([5][^4,6,9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$";
//    Pattern pattern = Pattern.compile(regex);
//    Matcher matcher = pattern.matcher(dto.getLoginName());
//    if(!matcher.matches()){
//      throw new OriginException("99999", "请输入正确的电话号码");
//    }
        //验证验证码是否有效
        String codeKey = dto.getCodeKey();
        String randomCode = dto.getRandomCode();
        if (CacheServiceFactory.getCacheService().get(codeKey) == null) {
            throw new OriginException("90000", "验证码已失效，请您重新输入");
        }
        String code = (String) CacheServiceFactory.getCacheService().get(codeKey);
        if (!code.equals(randomCode)) {
            log.error("验证码不正确.code:{},randomCode:{}", code, randomCode);
            CacheServiceFactory.getCacheService().del(codeKey);
            throw new OriginException("90000", "验证码已失效，请您重新输入");
        }
        //查询电话号码是否已经注册
        SysUser sum = new SysUser();
        sum.setLoginName(dto.getLoginName());
        int cnt = sysUserDao.selectCntByLoginName(sum);
        if (cnt > 0) {
            throw new OriginException("电话号码已经被人抢先注册了，请更换一个号码注册！");
        }
        //新增企业
        log.info("新增企业");
        SysCompany sysCompany = new SysCompany();
        sysCompany.setCpName(dto.getCpName());
        sysCompany.setContractTel(dto.getLoginName());
        sysCompany.setCpState(CommonConstant.CpState.INIT);
        String cpId = sysCompanyService.insertSelective(sysCompany);
        log.info("新增企业完成:{}", cpId);
        //开始新增用户
        log.info("新增用户");
        SysUserModel su = new SysUserModel();
        su.setLoginName(dto.getLoginName());
//    su.setPassword(Md5Encrypt.md5(dto.getPassword()));
        su.setPassword(dto.getPassword());
        su.setEntryTm(DateTimeUtil.getDate8());
        su.setState(CommonConstant.UserState.INIT);
//        su.setCpAdminFlag(CommonConstant.CpAdminFlag.YES);
        String userId = this.regUser(su);
        //插入用户公司表
        SysUserCp sysUserCp = new SysUserCp();
        sysUserCp.setUserId(userId);
        sysUserCp.setCpId(cpId);
        sysUserCpService.insertSelective(sysUserCp);
        log.info("新增用户完成");

    }

    @Override
    @Transactional(value = "db1", rollbackFor = Exception.class)
    public void batchWriteUser(String filePath) {
        String result = "";
        List<Map<String, Object>> list = ExcelUtil.readExcel(filePath);
        //新增用户信息
        String batchId = DateTimeUtil.getDateTime14();
//    int i =0;
        for (Map<String, Object> map : list) {
            String userId = sysSeqService.getTabSeq("SysUser", 4, null);
            //新增用户
            Map userMap = new HashMap();
            userMap.put("userId", userId);
            userMap.put("loginName", new BigDecimal(map.get("电话号码").toString()).toPlainString());
            userMap.put("userName", map.get("用户姓名").toString());
//      userMap.put("password",Md5Encrypt.md5(new BigDecimal(map.get("电话号码").toString()).toPlainString()));
            userMap.put("password", new BigDecimal(map.get("电话号码").toString()).toPlainString());
//      userMap.put("orgId",map.get("所在部门").toString());
            userMap.put("entryTm", new BigDecimal(map.get("入职时间(如20220101)").toString()).toPlainString());
//      userMap.put("cpId",super.getUserCpId());
            userMap.put("initPswdFlag", "1");
            userMap.put("state", "1");
            userMap.put("batchId", batchId);
            userMap.put("cpAdminFlag", "2");
            userMap.put("createUserId", super.getLoginUserId());
            sysUserDao.insertMap(userMap);

            //新增t_sys_user_cp
            SysUserCp sysUserCp = new SysUserCp();
            sysUserCp.setUserId(userId);
            sysUserCp.setCpId(super.getUserCpId());
//            sysUserCp.setOrgId(map.get("所在部门").toString());
            sysUserCp.setCreateUserId(super.getLoginUserId());
            sysUserCpDao.insertSelective(sysUserCp);

            //新增t_sys_user_org
            String orgIds = map.get("所在部门").toString();
            if (StringUtil.isEmpty(orgIds)) {
                log.error("{}没有绑定部门", map.get("电话号码"));
                throw new OriginException("存在没有绑定部门的员工信息");
            }
            List<SysUserOrg> suoList = new ArrayList<>();
            for (String orgId : orgIds.split(",")) {
                SysUserOrg suo = new SysUserOrg();
                suo.setUserId(userId);
                suo.setCpId(super.getUserCpId());
                suo.setOrgId(orgId);
                suoList.add(suo);
            }
            sysUserOrgDao.insertBatch(suoList);

            //新增角色
            String roleCodes = map.get("角色(多个角色用逗号分割)").toString();
            for (String roleCode : roleCodes.split(",")) {
                if (StringUtil.isEmpty(roleCode)) {
                    continue;
                }
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleCode(roleCode);
                sysUserRole.setCpId(super.getUserCpId());
                sysUserRole.setCreateUserId(super.getLoginUserId());
                sysUserRoleDao.insertSelective(sysUserRole);
            }

            //新增用户附加信息
            SysUserAdd sysUserAdd = new SysUserAdd();
            sysUserAdd.setUserId(userId);
            if (map.get("收款方式(1:网银;2:微信;3:支付宝)") != null) {
                sysUserAdd.setRecType(map.get("收款方式(1:网银;2:微信;3:支付宝)").toString().replace(".0", ""));
            }
            if (map.get("结算银行卡号(微信支付宝填手机号)") != null) {
                sysUserAdd.setBankCardNo(map.get("结算银行卡号(微信支付宝填手机号)").toString());
            }
            if (map.get("结算银行开户行") != null) {
                sysUserAdd.setBankName(map.get("结算银行开户行").toString());
            }
            if (map.get("结算银行开户行") != null) {
                sysUserAdd.setBankBranceName(map.get("结算银行开户行").toString());
            }
            if (map.get("结算银行开户分行") != null) {
                sysUserAdd.setBankUserName(map.get("结算银行开户分行").toString());
            }
            if (map.get("已缴纳押金(数字)") == null) {
                sysUserAdd.setDepositMoney(new BigDecimal(0));
            } else {
                sysUserAdd.setDepositMoney(new BigDecimal(map.get("已缴纳押金(数字)").toString()));
            }
            if (map.get("应缴押金金额(数字)") == null) {
                sysUserAdd.setStandardDepositMoney(new BigDecimal(0));
            } else {
                sysUserAdd.setStandardDepositMoney(new BigDecimal(map.get("应缴押金金额(数字)").toString()));
            }
            sysUserAdd.setCreateUserId(super.getLoginUserId());
            sysUserAddDao.insertSelective(sysUserAdd);

//      i++;
//      if(i%1000==0){
//        try {
//          sqlSession.commit();
//        }catch (Exception e){
//          log.error("commit.error:{}",e);
//        }finally {
//          sqlSession.close();
//        }
//      }
        }
//    try {
//      sqlSession.commit();
//    }catch (Exception e){
//      log.error("commit.error:{}",e);
//    }finally {
//      sqlSession.close();
//    }
    }


//  @Override
//  public String getCurUserOrgId(){
//    String userId = super.getLoginUserId();
//    SysUserModel su = new SysUserModel();
//    su.setUserId(userId);
//    su.setUserCpId(super.getUserCpId());
//    SysUserModel sum = sysUserDao.selectByPrimaryKey(su);
//    if(sum==null){
//      return "无";
//    }
//    return sum.getOrgId();
//  }


    @Override
    public SysUserModel getCurUserInfo() {
        String userId = super.getLoginUserId();
        SysUserModel su = new SysUserModel();
        su.setUserId(userId);
        su.setCpId(super.getUserCpId());
        SysUserModel sum = sysUserDao.selectByPrimaryKey(su);
        return sum;
    }

    @Override
    public List<SysRole> chkUserSOFlag(String userId) {
        SysUserModel su = new SysUserModel();
        su.setUserId(userId);
        SysUserModel sysUserModel = this.selectByPrimaryKey(su);
        if (sysUserModel == null) {
            throw new OriginException("员工信息不存在，操作失败");
        }
        List<SysRole> list = new ArrayList<>();
        String roleCodes = sysUserModel.getRoleCodes();
        for (String roleCode : roleCodes.split(",")) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleCode(roleCode);
            sysRole.setCpId(super.getUserCpId());
            SysRole sr = sysRoleDao.selectByCode(sysRole);
            list.add(sr);
        }
        return list;
//    String roleTypes = "";
//    for (String roleCode : roleCodes.split(",")) {
//      if (StringUtil.isEmpty(roleCode)) {
//        continue;
//      }
//      SysRole sysRole = new SysRole();
//      sysRole.setRoleCode(roleCode);
//      SysRole record = sysRoleService.selectByRoleCode(sysRole);
//      roleTypes += record.getRoleType() + ",";
//    }
//    boolean soFlag = false;
//    for (String roleType : roleTypes.split(",")) {
//      if (StringUtil.isEmpty(roleType)) {
//        continue;
//      }
//      if (CommonConstant.RoleType.OFFICE.equals(roleType) || CommonConstant.RoleType.STORE.equals(roleType)) {
//        soFlag = true;
//      }
//    }
//    return soFlag;
    }

    @Override
    public List<SysUserModel> selectListByRoleType(SysUserModel sysUser) {
        sysUser.setCpId(super.getUserCpId());
        sysUser.setRoleType(CommonConstant.RoleType.WORKER);
        List<SysUserModel> list = sysUserDao.selectListByRoleType(sysUser);
        return list;
    }

    @Override
    public String createRegCode(SysUser sysUser) {
        String randomCode = StringUtil.getCode(4, 0);
        log.info("vCode:" + randomCode);
        try {
            //正式环境才会走短信接口
            if (!"dev".equals(environment)) {
//        SmsClient.SendAliyunCode("武汉阿冬装饰工程有限公司",sysUser.getPhone(),"SMS_299760733","{ \"code\":\""+randomCode+"\"}");
//        SmsClient.SendAliyunCode("天津航链数字科技",sysUser.getPhone(),"SMS_296230346","{ \"code\":\""+randomCode+"\"}");
            } else {
                randomCode = "1111";
            }
            CacheServiceFactory.getCacheService().set(sysUser.getPhone() + "_code", randomCode, 130);
        } catch (Exception e) {
            log.error("createRegCode.error:{}", e);
            throw new OriginException("99999", "获取验证码失败");
        }
        return randomCode;
    }

}

